<?php
/**
 * 
 * @param string $str
 * @param obj $sentanceModel the model layer
 */
function parsesentancebk($sentence,$vocabularyArr){

    foreach ($vocabularyArr as $k=>$voabulary){
        $vocabularies=resortVocabularies($voabulary);
        $tempSentence=$sentence[$k];
        foreach($vocabularies as $key=>$_vocabulary){
            $tempSentence['source']=preg_replace("/($_vocabulary)/i","<$key>",$tempSentence['source']);
        }
       
        preg_match_all('/<([^>])>|([^<>0-9]) /',$tempSentence['source'],$matches);
        $sourceArr_temp=$matches[1];
       // var_dump($matches);die;
        foreach($sourceArr_temp as $k1=>$v1){
            $sourceArr[]=$vocabularies[$v1];
        }
        $sentence[$k]['source']=$sourceArr;
/*        foreach($vocabularies as $key=>$vocabulary){
            
            $tempSentance=preg_replace("/<$key>/i","<span>".$vocabulary."</span>",$tempSentance);
        
        }
        
        $sentanceResult=$tempSentance;*/
    }
    return $sentence;
}

function fillContent($vocabulary){
	$htmlContent=<<<EOF
		</li><li><span>{$vocabulary['source']}</span>
			<div class="popup">
				<table>
					<tr>
						<td>{$vocabulary['source']}</td>
					</tr>
					<tr>
						<td>{$vocabulary['source_phonetics']}</td>
					</tr>
					<tr>
						<td>{$vocabulary['target']}</td>
					</tr>

				</table>
			</div>
		</li><li>
EOF;

	return $htmlContent;
}


function parseSentence($sentence,$sentenceVocabularies,$speaker){

    $sortedVocabulaies=resortVocabularies($sentenceVocabularies);

    foreach($sortedVocabulaies as $key=>$vocabulary){
    	//echo $vocabulary['source'];
    	$vocSource=$vocabulary['source'];
        $sentence=preg_replace("/($vocSource)/i","<$key>",$sentence);
		//file_put_contents('d:\jpod.log',print_r($sentence,true)."\n",FILE_APPEND);
    }
    
    foreach($sortedVocabulaies as $key=>$vocabulary){
       
    	$htmlContent=fillContent($vocabulary);
        $sentence=preg_replace("/<$key>/i",$htmlContent,$sentence);
    }
    return "<ul><li style='margin-right:5px; width:80px;'>{$speaker}:".$sentence."</li></ul>";
}
/**
 * 
 * @param array $vocabularies
 * @param stirng $order in order to like order by id desc but not used 
 */
function resortVocabularies($vocabularies,$order=0){
    //$sortArr=array();
    $temp='';
    $size=count($vocabularies);
    for($i=0;$i<=$size-1;$i++){
        for($j=$size-1;$j>$i;$j--){
            if(strlen($vocabularies[$j]['source'])>=strlen($vocabularies[$j-1]['source'])){
                $temp=$vocabularies[$j];
                $vocabularies[$j]=$vocabularies[$j-1];
                $vocabularies[$j-1]=$temp;
            }
        }
    }
   // foreach($sortArr){}
    unset($temp);
    return $vocabularies;
}